package com.longrise.customview.photo;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.android.FormParameter;
import com.longrise.android.LFView;
import com.longrise.android.util.Util;
import com.longrise.customview.photo.bean.ImageFloder;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import static android.widget.GridView.STRETCH_COLUMN_WIDTH;

/**
 * Created by chengsan on 17/5/1.
 */

public class PhotoView extends LFView implements Handler.Callback
{
    private Context context;
    private LinearLayout panelView;
    private Button okBtn;
    private Button photosBtn;
    private GridView gridView;
    private PhotoAdapter photoAdapter;
    private PopupWindow popupWindow;

    /**
     * 存储文件夹中的图片数量
     */
    private int mPicsSize;
    /**
     * 图片数量最多的文件夹
     */
    private File mImgDir;
    /**
     * 所有的图片
     */
    private List<String> mImgs;

    /**
     * 临时的辅助类，用于防止同一个文件夹的多次扫描
     */
    private HashSet<String> mDirPaths = new HashSet<String>();

    /**
     * 扫描拿到所有的图片文件夹
     */
    private List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();
    int totalCount = 0;

    private Handler handler;

    private OnSelectImgFinishListener onSelectImgFinishListener;

    private int mode = 2 ;//照片选择模式 2:多张 1:单张
    private int maxSelectPhotoNum = 5;//一次最多可以选择多少张图片

    public PhotoView(Context c)
    {
        super(c);
        this.context = c;
    }

    /**
     * 照片选择模式 2:多张 1:单张
     * @param mode
     */
    public void setMode(int mode) {
        this.mode = mode;
    }

    /**
     * 一次最多可以选择多少张图片
     * @param maxSelectPhotoNum
     */
    public void setMaxSelectPhotoNum(int maxSelectPhotoNum) {
        this.maxSelectPhotoNum = maxSelectPhotoNum;
    }

    public Button getOkBtn() {
        return okBtn;
    }

    public void setOnSelectImgFinishListener(OnSelectImgFinishListener onSelectImgFinishListener) {
        this.onSelectImgFinishListener = onSelectImgFinishListener;
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public FormParameter getFormParameter() {
        return null;
    }

    @Override
    public void refresh() {

        loadData();
    }

    @Override
    public View getView()
    {
        return panelView;
    }

    @Override
    public void init() {

        handler = new Handler(this);
        initUI();
    }

    private void initUI()
    {
        panelView = new LinearLayout(context);
        panelView.setOrientation(LinearLayout.VERTICAL);

        //================菜单=====================
        LinearLayout menuLayout = new LinearLayout(context);
        menuLayout.setOrientation(LinearLayout.HORIZONTAL);
        menuLayout.setGravity(Gravity.CENTER_VERTICAL);
        menuLayout.setBackgroundColor(Color.parseColor("#2296e7"));
        panelView.addView(menuLayout, LinearLayout.LayoutParams.MATCH_PARENT, Util.dip2px(context,44));

        photosBtn = new Button(context);
        photosBtn.setBackgroundColor(Color.parseColor("#002296e7"));
        photosBtn.setText("相册");
        photosBtn.setTextColor(Color.WHITE);
        photosBtn.setPadding(Util.dip2px(context,5),0,Util.dip2px(context,5),0);
        LinearLayout.LayoutParams photoLP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        photoLP.rightMargin = Util.dip2px(context,6);
        menuLayout.addView(photosBtn, photoLP);
        photosBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                showPop();
            }
        });

        //标题
        TextView titleView = new TextView(context);
        titleView.setTextColor(Color.WHITE);
        titleView.setTextSize(18f);
        titleView.setGravity(Gravity.CENTER);
        titleView.setText("照片");
        LinearLayout.LayoutParams titleLP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
        titleLP.weight = 1;
        menuLayout.addView(titleView, titleLP);

        okBtn = new Button(context);
        okBtn.setBackgroundColor(Color.parseColor("#002296e7"));
        okBtn.setText("确定(0)");
        okBtn.setTextColor(Color.WHITE);
        okBtn.setPadding(Util.dip2px(context,5),0,Util.dip2px(context,5),0);
        LinearLayout.LayoutParams personLP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        personLP.rightMargin = Util.dip2px(context,6);
        menuLayout.addView(okBtn, personLP);
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                ok();
                closeForm();
            }
        });

        //=================================
        RelativeLayout relativeLayout = new RelativeLayout(context);
        panelView.addView(relativeLayout, LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);

        //gridView
        gridView = new GridView(context);
        gridView.setCacheColorHint(Color.parseColor("#00000000"));
        gridView.setClipChildren(true);
        gridView.setGravity(Gravity.CENTER);
        gridView.setHorizontalSpacing(Util.dip2px(context,3));
        gridView.setNumColumns(3);
        //stretchMode属性值的作用是设置GridView中的条目以什么缩放模式去填充剩余空间。
        gridView.setStretchMode(STRETCH_COLUMN_WIDTH);
        gridView.setVerticalSpacing(Util.dip2px(context,3));
        relativeLayout.addView(gridView,RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT);

        photoAdapter = new PhotoAdapter(context,mode,maxSelectPhotoNum);
        photoAdapter.setHandler(handler);
        photoAdapter.setImages(mImgs);
        gridView.setAdapter(photoAdapter);

        /*
        RelativeLayout dirLayout = new RelativeLayout(context);
        dirLayout.setBackgroundColor(Color.parseColor("#e0000000"));
        dirLayout.setClickable(true);
        RelativeLayout.LayoutParams dirLP = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,Util.dip2px(context,50));
        dirLP.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        relativeLayout.addView(dirLayout,dirLP);


        TextView dirText = new TextView(context);
        dirText.setText("所有图片");
        dirText.setTextColor(Color.WHITE);
        dirText.setPadding(Util.dip2px(context,10),0,0,0);
        dirText.setGravity(Gravity.CENTER_VERTICAL);
        RelativeLayout.LayoutParams dirTextLP = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);
        dirTextLP.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        dirLayout.addView(dirText,dirTextLP);


        TextView totalConutText = new TextView(context);
        totalConutText.setText("0张");
        totalConutText.setTextColor(Color.WHITE);
        totalConutText.setGravity(Gravity.CENTER_VERTICAL);
        RelativeLayout.LayoutParams totalLP = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);
        totalLP.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        dirLayout.addView(totalConutText,totalLP);
        */

    }

    public void ok()
    {
        if(null != photoAdapter)
        {
            if(photoAdapter.getmSelectedImage() == null || photoAdapter.getmSelectedImage().size() <= 0)
            {
                Toast.makeText(context,"请选择图片",Toast.LENGTH_SHORT).show();
                return;
            }

            if(null != onSelectImgFinishListener)
            {
                onSelectImgFinishListener.onSelectFinish(this,photoAdapter.getmSelectedImage());
            }

        }
    }

    private void loadData()
    {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED))
        {
            Toast.makeText(context, "暂无外部存储", Toast.LENGTH_SHORT).show();
            return;
        }

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {

                try {

                    String firstImage = null;

                    Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    ContentResolver mContentResolver = context.getContentResolver();

                    // 只查询jpeg和png的图片
                    Cursor mCursor = mContentResolver.query(mImageUri, null,
                            MediaStore.Images.Media.MIME_TYPE + "=? or "
                                    + MediaStore.Images.Media.MIME_TYPE + "=?",
                            new String[]{"image/jpeg", "image/png"},
                            MediaStore.Images.Media.DATE_MODIFIED);

                    Log.e("TAG", mCursor.getCount() + "");
                    while (mCursor.moveToNext()) {
                        // 获取图片的路径
                        String path = mCursor.getString(mCursor
                                .getColumnIndex(MediaStore.Images.Media.DATA));

                        Log.e("TAG", path);
                        // 拿到第一张图片的路径
                        if (firstImage == null)
                            firstImage = path;
                        // 获取该图片的父路径名
                        File parentFile = new File(path).getParentFile();
                        if (parentFile == null)
                            continue;
                        String dirPath = parentFile.getAbsolutePath();
                        ImageFloder imageFloder = null;
                        // 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
                        if (mDirPaths.contains(dirPath)) {
                            continue;
                        } else {
                            mDirPaths.add(dirPath);
                            // 初始化imageFloder
                            imageFloder = new ImageFloder();
                            imageFloder.setDir(dirPath);
                            imageFloder.setFirstImagePath(path);
                        }

                        int picSize = parentFile.list(new FilenameFilter() {
                            @Override
                            public boolean accept(File dir, String filename) {
                                if (filename.endsWith(".jpg")
                                        || filename.endsWith(".png")
                                        || filename.endsWith(".jpeg"))
                                    return true;
                                return false;
                            }
                        }).length;
                        totalCount += picSize;

                        imageFloder.setCount(picSize);
                        mImageFloders.add(imageFloder);

                        if (picSize > mPicsSize) {
                            mPicsSize = picSize;
                            mImgDir = parentFile;
                        }
                    }
                    mCursor.close();

                    // 扫描完成，辅助的HashSet也就可以释放内存了
                    mDirPaths = null;

                    if (null != handler) {
                        // 通知Handler扫描图片完成
                        handler.sendEmptyMessage(100);
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public boolean handleMessage(Message message)
    {
        switch (message.what)
        {
            case 100:
            {
                // 为View绑定数据
                data2View();
                break;
            }
            case  200:
            {
                int num = message.arg1;
                if(null != okBtn)
                {
                    okBtn.setText("完成(" + num + ")");
                }
                break;
            }
        }
        return false;
    }

    /**
     * 为View绑定数据
     */
    private void data2View()
    {
        if (mImgDir == null)
        {
            Toast.makeText(context, "没有扫描到图片", Toast.LENGTH_SHORT).show();
            return;
        }

        mImgs = Arrays.asList(mImgDir.list());
        /**
         * 可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
         */
        if(null != photoAdapter)
        {
            if(null != mImgDir)
            {
                photoAdapter.setmDirPath(mImgDir.getAbsolutePath());
            }
            photoAdapter.setImages(mImgs);
            photoAdapter.notifyDataSetChanged();
        }
        /*
        photoAdapter = new PhotoAdapter(context, mImgs,
                R.layout.grid_item, mImgDir.getAbsolutePath());
        mGirdView.setAdapter(mAdapter);
        */
        //mImageCount.setText(totalCount + "张");
    }


    /**
     * 显示相册列表
     */
    private void showPop()
    {
        if(popupWindow == null)
        {

            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            linearLayout.setBackgroundColor(Color.parseColor("#00000000"));
            linearLayout.setGravity(Gravity.BOTTOM);
            linearLayout.setClickable(true);
            linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if(null != popupWindow)
                    {
                        popupWindow.dismiss();
                    }
                }
            });

            PhotoListAapter photoListAapter = new PhotoListAapter(context);
            photoListAapter.setmImageFloders(mImageFloders);

            ListView listView = new ListView(context);
            listView.setBackgroundColor(Color.parseColor("#DD000000"));
            listView.setDivider(new ColorDrawable(Color.parseColor("#FFFFFF")));
            listView.setDividerHeight(1);
            linearLayout.addView(listView,LayoutParams.MATCH_PARENT,(int)(Util.getScreenHeight(context) * 0.6));
            listView.setAdapter(photoListAapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                    if(null != mImageFloders)
                    {
                        ImageFloder imageFloder = mImageFloders.get(i);
                        if(null != imageFloder)
                        {
                            mImgDir = new File(imageFloder.getDir());
                            mImgs = Arrays.asList(mImgDir.list(new FilenameFilter()
                            {
                                @Override
                                public boolean accept(File dir, String filename)
                                {
                                    if (filename.endsWith(".jpg") || filename.endsWith(".png")
                                            || filename.endsWith(".jpeg"))
                                        return true;
                                    return false;
                                }
                            }));
                            /**
                             * 可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
                             */
                            if(null != photoAdapter)
                            {
                                if(null != mImgDir)
                                {
                                    photoAdapter.setmDirPath(mImgDir.getAbsolutePath());
                                }
                                photoAdapter.setImages(mImgs);
                                photoAdapter.notifyDataSetChanged();
                            }
                            popupWindow.dismiss();
                        }
                    }

                }
            });

            popupWindow = new PopupWindow(linearLayout,LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
            popupWindow.setTouchable(true);
            popupWindow.setFocusable(true);
            //需要设置为ture，表示可以聚焦
            // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
            // 我觉得这里是API的一个bug
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
            popupWindow.setOutsideTouchable(true);
        }

        popupWindow.showAtLocation(panelView,Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,0);
        //设置位于指定控件得下面，参数：相对得控件/X偏移量，Y偏移量
        //popupWindow.showAsDropDown(commonTitleView,Util.getScreenWidth(context)-popWidth-Util.dip2px(context,5) ,0);
    }



    public interface OnSelectImgFinishListener
    {
        void onSelectFinish(PhotoView photoView,List<String> list);
    }
}
